import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import authService from '../services/authService';
import type { User as SupabaseUser, Session } from '@supabase/supabase-js';

interface UserProfile {
  id: string;
  email: string;
  name?: string;
  role: string;
  avatar_url?: string;
  created_at: string;
  updated_at: string;
}

interface User extends SupabaseUser {
  profile?: UserProfile;
}

interface AuthState {
  // 状态
  user: User | null;
  session: Session | null;
  profile: UserProfile | null;
  isAuthenticated: boolean;
  loading: boolean;
  initialized: boolean;

  // 操作方法
  setUser: (user: User | null) => void;
  setSession: (session: Session | null) => void;
  setProfile: (profile: UserProfile | null) => void;
  setLoading: (loading: boolean) => void;
  setInitialized: (initialized: boolean) => void;
  
  // 认证方法
  signIn: (email: string, password: string) => Promise<any>;
  signUp: (email: string, password: string, name?: string) => Promise<any>;
  signOut: () => Promise<void>;
  refreshSession: () => Promise<void>;
  initialize: () => Promise<void>;
  
  // 重置状态
  reset: () => void;
}

const initialState = {
  user: null,
  session: null,
  profile: null,
  isAuthenticated: false,
  loading: false,
  initialized: false,
};

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      ...initialState,

      // 状态设置方法
      setUser: (user) => set({ user, isAuthenticated: !!user }),
      setSession: (session) => set({ session }),
      setProfile: (profile) => set({ profile }),
      setLoading: (loading) => set({ loading }),
      setInitialized: (initialized) => set({ initialized }),

      // 登录
      signIn: async (email: string, password: string) => {
        set({ loading: true });
        
        try {
          const response = await authService.signIn(email, password);
          
          if (response.success && response.data) {
            const { user, session, profile } = response.data;
            
            set({
              user: user as User,
              session,
              profile: profile || null,
              isAuthenticated: true,
              loading: false,
            });
          } else {
            set({ loading: false });
          }
          
          return response;
        } catch (error) {
          set({ loading: false });
          throw error;
        }
      },

      // 注册
      signUp: async (email: string, password: string, name?: string) => {
        set({ loading: true });
        
        try {
          const response = await authService.signUp(email, password, { name });
          
          if (response.success && response.data) {
            const { user, session, profile } = response.data;
            
            set({
              user: user as User,
              session,
              profile: profile || null,
              isAuthenticated: true,
              loading: false,
            });
          } else {
            set({ loading: false });
          }
          
          return response;
        } catch (error) {
          set({ loading: false });
          throw error;
        }
      },

      // 登出
      signOut: async () => {
        set({ loading: true });
        
        try {
          await authService.signOut();
        } catch (error) {
          console.error('登出失败:', error);
        } finally {
          // 无论登出是否成功，都清除本地状态
          get().reset();
        }
      },

      // 刷新会话
      refreshSession: async () => {
        try {
          const { session: newSession, user: newUser } = await authService.refreshSession();
          
          if (newSession && newUser) {
            set({
              session: newSession,
              user: newUser as User,
              isAuthenticated: true,
            });
          } else {
            get().reset();
          }
        } catch (error) {
          console.error('刷新会话失败:', error);
          get().reset();
        }
      },

      // 初始化认证状态
      initialize: async () => {
        if (get().initialized) {
          return;
        }

        set({ loading: true });
        
        try {
          // 获取当前会话
          const currentSession = await authService.getCurrentSession();
          
          if (currentSession) {
            // 如果有会话，更新状态
            set({
              session: currentSession,
              user: currentSession.user as User,
              isAuthenticated: true,
            });
            
            // 这里可以获取用户配置文件
            // const profile = await getUserProfile(currentSession.user.id);
            // if (profile) {
            //   set({ profile });
            // }
          } else {
            // 如果没有会话，清除状态
            get().reset();
          }
        } catch (error) {
          console.error('初始化认证状态失败:', error);
          get().reset();
        } finally {
          set({ loading: false, initialized: true });
        }
      },

      // 重置状态
      reset: () => set({
        ...initialState,
        initialized: true, // 保持初始化状态
      }),
    }),
    {
      name: 'auth-storage', // localStorage 中的 key
      storage: createJSONStorage(() => localStorage),
      // 只持久化必要的状态，不持久化 loading 等临时状态
      partialize: (state) => ({
        user: state.user,
        session: state.session,
        profile: state.profile,
        isAuthenticated: state.isAuthenticated,
      }),
      // 版本控制，用于处理存储结构变更
      version: 1,
    }
  )
);

// 监听 Supabase 认证状态变化
let authStateListener: any = null;

export const initializeAuthListener = () => {
  if (authStateListener) {
    return; // 避免重复初始化
  }

  authStateListener = authService.onAuthStateChange(async (event: string, session: Session | null) => {
    console.log('Auth state changed:', event, session);
    
    const { setSession, setUser, reset, setProfile } = useAuthStore.getState();
    
    if (event === 'SIGNED_IN' && session) {
      setSession(session);
      setUser(session.user as User);
      
      // 这里可以获取用户配置文件
      // const profile = await getUserProfile(session.user.id);
      // if (profile) {
      //   setProfile(profile);
      // }
    } else if (event === 'SIGNED_OUT') {
      reset();
    } else if (event === 'TOKEN_REFRESHED' && session) {
      setSession(session);
      setUser(session.user as User);
    }
  });
};

// 清理监听器
export const cleanupAuthListener = () => {
  if (authStateListener) {
    authStateListener.data.subscription.unsubscribe();
    authStateListener = null;
  }
};